import { createSlice, PayloadAction, createAsyncThunk } from '@reduxjs/toolkit';
import type { RootState } from '../store';

// Define a type for the slice state
interface initialState {
    value: number;
}

// Define the initial state using that type
const initialState = {
    value: 0,
} as initialState;

const fetchData = createAsyncThunk('counter/fetchData', async () => await new Promise(() => {}));

export const reducerSlice = createSlice({
    name: 'counter', // nameSpace
    initialState,
    reducers: {
        increment: (state) => {
            state.value += 1;
        },
        decrement: (state) => {
            state.value -= 1;
        },
        incrementByAmount: (state, action: PayloadAction<number>) => {
            state.value += action.payload;
        },
    },
    extraReducers: {
        [fetchData.fulfilled.type]: (state: initialState, action: PayloadAction<initialState>) => {
            state.value = action.payload.value;
        },
    },
});

export const { increment, decrement, incrementByAmount } = reducerSlice.actions;

// Other code such as selectors can use the imported `RootState` type
export const selectCount = (state: RootState) => state.counter.value;

export default reducerSlice.reducer;
